package com.atlinmengze.java.ai.langchain4j.controller;

import com.atlinmengze.java.ai.langchain4j.assistant.XiaozhiAgent;
import com.atlinmengze.java.ai.langchain4j.bean.ChatForm;
import com.atlinmengze.java.ai.langchain4j.tools.DepressionAssessmentTools;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

@Tag(name = "Asclepius")
@RestController
@RequestMapping("/xiaozhi")
public class XiaozhiController {

    @Autowired
    private XiaozhiAgent xiaozhiAgent;

    @Autowired
    private DepressionAssessmentTools depressionAssessmentTools;

    // 记录每个 memoryId 是否在自评流程中
    private final Map<Long, Boolean> phq9SessionMap = new ConcurrentHashMap<>();

    /**
     * 大智聊天入口
     * @param chatForm
     * @return
     */
    @Operation(summary = "对话")
    @PostMapping(value = "/chat", produces = "text/stream;charset=utf-8")
    public Flux<String> chat(@RequestBody ChatForm chatForm)  {
        Long memoryId = chatForm.getMemoryId();
        String message = chatForm.getMessage();
        // 1. 检查是否在自评流程中
        if (Boolean.TRUE.equals(phq9SessionMap.get(memoryId))) {
            // 尝试解析用户输入为选项序号
            int optionIndex = parseOptionIndex(message);
            if (optionIndex >= 1 && optionIndex <= 4) {
                String result = depressionAssessmentTools.answerPHQ9(memoryId, optionIndex);
                // 如果自评结束，移除标记
                if (result.contains("自评完成")) {
                    phq9SessionMap.remove(memoryId);
                }
                return Flux.just(result);
            } else {
                return Flux.just("请输入有效的选项序号（1-4）");
            }
        }
        // 2. 检查是否触发自评
        if (message.contains("抑郁自评") || message.contains("我要做自评") || message.contains("PHQ-9")) {
            phq9SessionMap.put(memoryId, true);
            String firstQ = depressionAssessmentTools.startPHQ9(memoryId);
            return Flux.just(firstQ);
        }
        // 3. 走原有 AI 聊天流程
        return xiaozhiAgent.chat(memoryId, message);
    }

    // 辅助方法：解析用户输入为选项序号
    private int parseOptionIndex(String msg) {
        try {
            return Integer.parseInt(msg.trim());
        } catch (Exception e) {
            return -1;
        }
    }
}